<template>
  <PageModal
    prevent-back
    :show="showModal"
    :back-text="backText"
    :title="$t('Appliance.OrderProgram.Title.Text')"
    :footer-size="footerSize"
    :footer-style="footerStyle"
    @back="emit('back')"
  >
    <HighlightView v-if="initialized" :title="activeProgramName" :title-remark="activeProgramRemainingText">
      <template #desc>
        <text v-for="name in activedParameterNames" :key="name">{{ name }}</text>
      </template>

      <ParameterCard :title="$t('Appliance.OrderProgram.SelectTime.Title.Text')" :value="null">
        <template #desc>
          <block v-if="isSetValleyTime">
            <view class="valley-time">
              <text>{{ $t('Appliance.OrderProgram.ValleyTime.Text') }} {{ valleyTime }}</text>
            </view>
            <view class="valley-time-suggestion enabled">
              <view class="valley-des">{{ $t('Appliance.OrderProgram.ValleyTime.Enabled.Text') }}</view>
              <view v-if="relativeData && relativeData.type !== 'Finish'" class="valley-set" @click="toValleyTime">{{
                $t('Appliance.OrderProgram.ValleyTime.ToValleyTime.Button.Text')
              }}</view>
            </view>
          </block>
          <view v-else class="valley-time-suggestion">
            <view class="valley-des">{{ $t('Appliance.OrderProgram.ValleyTime.Suggestion.Text') }}</view>
            <view class="valley-set" @click="jumpCommonSet">{{
              $t('Appliance.OrderProgram.ValleyTime.ToSetting.Button.Text')
            }}</view>
            <image class="valley-icon" mode="aspectFit" src="/static/EnterLink.png"></image>
          </view>
        </template>

        <view class="order-picker">
          <view class="picker-body">
            <view class="prefix">{{
              $t(isTodaySelected ? 'Appliance.OrderProgram.Today.Text' : 'Appliance.OrderProgram.Tomorrow.Text')
            }}</view>
            <view class="picker">
              <TimePicker
                :value="selectedTime"
                :start="selectableStartTime"
                :end="selectableEndTime"
                :interval="orderInterval"
                @change="onPickerTimeChange"
              />
            </view>
            <view class="suffix">
              <block v-if="relativeData">{{
                $t(
                  relativeData.type === 'Finish'
                    ? 'Appliance.OrderProgram.FinishInRelative.Text'
                    : 'Appliance.OrderProgram.StartInRelative.Text'
                )
              }}</block>
              <block v-else>--</block>
            </view>
          </view>
          <view class="picker-footer remaining-time">
            <!-- 预计结束时间 -->
            <text v-if="relativeData">{{ relativeData.estimatedTimeLabel }}</text>
            <text v-else>{{ $t('Appliance.OrderProgram.EstimatedFinishTime.Text') }}</text>

            <text class="time-text">{{ relativeData?.estimatedTime || '--' }}</text>
          </view>
        </view>
      </ParameterCard>
    </HighlightView>

    <template #footer>
      <TextButton
        vibrate
        size="large"
        :text="$t('APP.Common.Confirm.Text')"
        :disabled="isOffline === true"
        :plain-disabled="orderDisabled || startDisabled || !selectedTime || !relativeData"
        @click="onConfirm"
      />
    </template>
  </PageModal>
</template>

<script setup lang="ts">
import PageModal from '@/common/pageModal.vue'
import TextButton from '@/common/textButton.vue'
import type { BaseController } from '@/controller/BaseAppliance/definition'
import { useOrderTime } from '../useOrderTime'
import TimePicker, { type ChangePayload } from '../../components/timePicker.vue'
import { useAccountStore } from '@/store/account'
import type { ProgramSelectOption } from '@/api/appliance'
import HighlightView from '../../components/highlightView.vue'
import { useControlState } from '@/controller/BaseAppliance/useControl'
import { footerSize, footerStyle } from '@/layout/appliance/style'
import { nextTickPromise, toPage } from '@/utils/mpHelper'
import { trackEvent, TrackType } from '@/dataReport/tracks'
import { safeTrack } from '@/dataReport/dataReportUtil'
import ParameterCard from '../../components/parameterCard.vue'

const props = defineProps<{
  show: boolean
  control: BaseController.Control
  usingValleyTime?: boolean // 是否初始停留在谷电时间范围内
  backText?: string
  /**
   * 调节参数配置
   */
  activedParameterNames: string[] // 显示当前启用的参数名称
  activedParameterOption: unknown[] // 显示当前启用的参数名称
}>()
const emit = defineEmits<{
  (e: 'update:show', show: boolean): void
  (e: 'confirm', options: ProgramSelectOption[], trackData: any): void
  (e: 'close'): void
  (e: 'back'): void
  (e: 'to-adjust'): void
  (e: 'to-select-time'): void
}>()

const accountStore = useAccountStore()
const { isOffline, orderDisabled, startDisabled } = useControlState(props.control)
const initialized = ref(false)

/**
 * 选择程序
 */
const activeProgramName = computed(() => props.control.store.currentProgramName)
// 程序剩余时间
const activeProgramRemainingText = computed(() => props.control.store.programRemainingText)

/**
 * 选择时间
 */
const {
  selectableStartTime,
  selectableEndTime,
  initSelectableTime,
  isTodaySelected,
  selectedTime,
  setSelectTime,
  selectBeginTime,
  selectValleyTime,
  relativeData,
  orderInterval, // 预约时间选择间隔 (单位: 秒)
  getOrderOptions,
} = useOrderTime(props.control)

let timePickerTimestamp = ''
function onPickerTimeChange(payload: ChangePayload) {
  timePickerTimestamp = payload.text
  setSelectTime(payload.timestamp)
}

const showModal = ref(false)
watchEffect(async () => {
  if (props.show) {
    initialized.value = true
    await nextTickPromise()
  }
  showModal.value = props.show
})

watch(
  () => props.show,
  (show) => show && initTime()
)
watch(
  () => props.control.store.programRemaining,
  () => props.show && initTime()
)

function initTime() {
  // 初始化启动时间
  initSelectableTime()
  // 初始化时间选择
  initBeginTimeSelection()
}

function initBeginTimeSelection() {
  // 初始化时间定位到谷电时间
  if (props.usingValleyTime && relativeData.value) {
    selectValleyTime()
    return
  } else {
    // 设为起始时间
    selectBeginTime()
  }
}

function onConfirm() {
  safeTrack(() => {
    type TrackData = {
      program_key: string
      [key: string]: unknown
      reserve_time_range: string
    }

    const trackData: TrackData = {
      program_key: '',
      program_name: '',
      reserve_time_range: '',
    }
    trackData.reserve_time_range = `${relativeData.value?.estimatedTime}-${timePickerTimestamp}`
    trackData.program_key = props.control.store.currentProgramKey
    trackData.program_name = props.control.store.currentProgramName
    props.activedParameterOption.map((items, index) => {
      trackData[`option_obj_${index + 1}`] = items
    })

    //trackEvent('reserve_program', trackData, TrackType.ApplianceDetail)
    emit('confirm', getOrderOptions(), trackData)
  })
}
/**
 * 谷电时间
 */
const isSetValleyTime = computed(() => accountStore.isSetValleyTime)
const valleyTime = computed(() => `${accountStore.valleyElecStartTime}-${accountStore.valleyElecEndTime}(次日)`)
// 跳转通用设置页面
function jumpCommonSet() {
  toPage('/pages/my/generalSetting/generalSetting')
}
// 定位到谷电时间
function toValleyTime() {
  selectValleyTime({ stayTimeWithinValleyTime: true })
}
</script>

<style scoped lang="less">
.valley-time {
  font-weight: 500;
  font-size: 28rpx;
  color: #41c38c;
  + .valley-time-suggestion {
    margin-top: 12rpx;
  }
}
.valley-time-suggestion {
  display: flex;
  align-items: center;
  &.enabled {
    .valley-des {
      color: var(--primary-color);
      font-weight: 400;
      margin-right: 16rpx;
    }
  }
  .valley-des {
    font-weight: 500;
    font-size: 28rpx;
    line-height: 40rpx;
    color: #41c38c;
    margin-right: 24rpx;
  }
  .valley-set {
    font-weight: 500;
    font-size: 28rpx;
    line-height: 40rpx;
    text-decoration-line: underline;
    color: var(--primary-color);
    margin-right: 6rpx;
  }
  .valley-icon {
    width: 22rpx;
    height: 18rpx;
  }
}
.order-picker {
  padding: 12rpx 32rpx 24rpx;
  .picker-body {
    display: flex;
    justify-content: space-between;
    align-items: center;
    > .prefix,
    > .suffix {
      font-weight: 500;
      font-size: 32rpx;
      line-height: 44rpx;
      color: rgba(var(--dark-vector), 0.8);
    }
  }
  .picker-footer {
    margin-top: 48rpx;
  }
}
.remaining-time {
  font-weight: 500;
  font-size: 32rpx;
  line-height: 44rpx;
  color: rgba(var(--dark-vector), 0.8);
  .time-text {
    margin-left: 16rpx;
  }
}
</style>
